﻿using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;

namespace Fuse8.ContentManagementFramework.BizFacade.Services.Contents.Queryable
{
    public class SelectVisitor : ExpressionVisitor
    {
        readonly List<string> fieldsToSelect = new List<string>();
        public IList<string> ParseForSelects(Expression expression)
        {
            Visit(expression);

            return fieldsToSelect;
        }

        protected override Expression VisitConstant(ConstantExpression node)
        {
            var list = node.GetValueFromConst<string[]>();
            if (list != null)
            {
                fieldsToSelect.AddRange(list);            
            }            
            return base.VisitConstant(node);
        }

        protected override Expression VisitMember(MemberExpression node)
        {
            if (node.Expression.NodeType == ExpressionType.Constant)
            {
                var list = ((ConstantExpression) node.Expression).GetValueFromConst<string[]>(node.Member.Name);
                if (list != null)
                {
                    fieldsToSelect.AddRange(list);
                }           
            }
            return base.VisitMember(node);
        }
        
        protected override Expression VisitNew(NewExpression node)
        {
            foreach(var member in node.Members)
            {
                fieldsToSelect.Add(member.Name);
            }
            return base.VisitNew(node);
        }
    }
}